package com.wanxi.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : 林子淳
 * @create 2023/3/10 9:13
 */

public class UserSessionInterceptor implements HandlerInterceptor {
    //在目标方法执行之前 执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Handler) throws Exception {
        // 在拦截点执行前拦截，如果返回true则不执行拦截点后的操作（拦截成功）
        System.out.println("进入preHandle");
        ServletContext session = request.getServletContext();
//        HttpSession session = request.getSession();
        if(session.getAttribute("uu")!=null) {
            // 登录成功不拦截
            System.out.println("进入preHandle:登录成功不拦截username:"+session.getAttribute("uu"));
            return true;
        }else {
            // 拦截后进入登录页面
            //response.sendRedirect(request.getContextPath()+"/system/login");
            System.out.println("进入preHandle:拦截后进入登录页面username:"+session.getAttribute("uu"));
            response.sendRedirect(request.getContextPath()+"http://127.0.0.1:8081/html/login.html");
            return false;
        }
    }
    //在流程都执行完毕后 执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
            throws Exception {
        // 执行完毕，返回前拦截
        System.out.println("进入afterCompletion");
    }
    //在目标方法执行之后 视图对象返回之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
            throws Exception {
        // 在处理过程中，执行拦截
        System.out.println("进入postHandle");
    }
}
